const { v4: uuidv4 } = require('uuid');
let base_projectdetails = require("./models/base_projectdetails")(sequelize, DataTypes);
let base_conpermit_info = require("./models/base_conpermit_info")(sequelize, DataTypes);
let base_bidinfo = require("./models/base_bidinfo")(sequelize, DataTypes);
let base_project_subject = require("./models/base_project_subject")(sequelize, DataTypes);
// let base_project_area = require("./models/base_project_area")(sequelize, DataTypes);
let base_project_area = require("./models/base_map_project")(sequelize, DataTypes);
// consproject.hasMany(base_conpermit_info, {
//   sourceKey: "id",
//   foreignKey: "idConsproject",
// });
// base_conpermit_info.belongsTo(consproject, {
//   sourceKey: "id",
//   foreignKey: "idConsproject",
// });

// consproject.hasMany(base_project_subject, {
//   sourceKey: "id",
//   foreignKey: "idConsproject",
// });
// base_project_subject.belongsTo(consproject, {
//   sourceKey: "id",
//   foreignKey: "idConsproject",
// });

base_projectdetails.hasOne(base_bidinfo, {
  sourceKey: "contractConsCode",
  foreignKey: "KeyGUID",
});
base_bidinfo.belongsTo(base_projectdetails, {
  sourceKey: "contractConsCode",
  foreignKey: "KeyGUID",
});
// base_projectdetails.hasOne(base_project_area, {
//   sourceKey: "projectnoPt",
//   foreignKey: "PROJECTNO",
// });
// base_project_area.belongsTo(base_projectdetails, {
//   sourceKey: "projectnoPt",
//   foreignKey: "PROJECTNO",
// });
const utils = require("./utils");
const { Op } = require("sequelize");

async function getlist(req,where,order,attributes) {
  let r = await base_projectdetails.findAndCountAll({
    offset: ((req.query.pageNum ?? 1) - 1) * (req.query.pageSize ?? 0),
    limit: (req.query.pageSize ?? 100) * 1,
    where,
    include: [base_bidinfo],
    order,
    attributes
  });

  //添加一对多
  let rrows = [];
  for (let row of r.rows) {
    let rrow = row.toJSON();
    //基础施工许可
    rrow.base_conpermit_info_base = rrow.id?await sequelize.query(`select t2.* from base_projectdetails t1,(select *,row_number() over (partition by case when prjpwemits_num_base is null then  prjpwemits_num else prjpwemits_num_base end order by create_date desc) as rn from base_conpermit_info where id_consproject='${rrow.id}') t2 where t1.id = t2.id_consproject`,{
      model: base_conpermit_info,
      mapToModel: true
    }):[];
    // 全部施工许可
    // rrow.base_conpermit_info = rrow.id? await base_conpermit_info.findAll({ where: { 'idConsproject': rrow.id } }):[];
    rrow.base_project_subject = rrow.id? await base_project_subject.findAll({ where: { 'idConsproject': rrow.id } }):[];
    rrow.base_project_area =rrow.projectareaObjectid? await base_project_area.findOne({ where: { 'OBJECTID': parseInt(rrow.projectareaObjectid) } }) : {};
    rrows.push(rrow);
  };
  r.rows = rrows;
  return r;
}

app.get("/base_projectdetails/listmini", async (req, res) => {
  try {
    let where = utils.getwhere(req.query);
    utils.setlike(where,'projectName',req);
    utils.setlike(where,'projectAddress',req);
    where[Op.and].push({deletemark:0});
    let r = await base_projectdetails.findAndCountAll({
      offset: ((req.query.pageNum ?? 1) - 1) * (req.query.pageSize ?? 0),
      limit: (req.query.pageSize ?? 100) * 1,
      where,
      // include: [base_bidinfo],
      attributes:req.query.attributes?.split(',')
      // order
    });
    res.send(r);
  } catch (err) {
    console.log(err);
    res.send("err");
  }
});

app.get("/base_projectdetails/combine",async (req, res)=>{
  try {
    console.log(req.query)
    //删除合并项目
    await  sequelize.query(`update base_projectdetails set adminaccount = concat(adminaccount,';','${req.query.accounts}')  where ID = '${req.query.combineid}'`);
    //更新关联表的外键
    await  sequelize.query(`update base_conpermit_info set id_consproject='${req.query.combineid}' where id_consproject in ('${req.query.selsid.split(',').join("','")}')`);
    await  sequelize.query(`update base_project_subject set id_consproject='${req.query.combineid}' where id_consproject in ('${req.query.selsid.split(',').join("','")}')`);
    //删除合并项目
    await  sequelize.query(`update base_projectdetails set deletemark=1 where ID in ('${req.query.selsid.split(',').join("','")}')`);
    res.send('ok');
  } catch (err) {
    console.log(err);
    res.send("err");
  }
})

app.get("/base_projectdetails/repeatname", async (req, res) => {
  await repeatres(req, res,'projectName','project_name');
});

app.get("/base_projectdetails/repeatadmin", async (req, res) => {
  await repeatres(req, res,'adminaccount','adminaccount');
});
app.get("/base_projectdetails/repeatht", async (req, res) => {
  await repeatres(req, res,'contractConsCode','contract_cons_code');
});


app.get("/base_projectdetails/list", async (req, res) => {
  try {
    let where = utils.getwhere(req.query);
    utils.setlike(where,'projectName',req);
    utils.setlike(where,'projectAddress',req);
    where[Op.and].push({deletemark:0});
    let r = await getlistreq(req,where);
    res.send(r);
  } catch (err) {
    console.log(err);
    res.send("err");
  }
});

async function getlistreq(req,where){
  return await getlist(req,where,[['updatedTime', 'DESC']],req.query.attributes?.split(','));
}

//无落图查询
app.get("/base_projectdetails/noarea", async (req, res) => {
  try {
    let where = { 'projectarea_objectid': { [Op.is]:null },deletemark:0 };
    let r = await getlistreq(req,where);
    res.send(r);
  } catch (err) {
    console.log(err);
    res.send("err");
  }
});

app.get("/base_projectdetails/:id", async (req, res) => {
  let r = await base_projectdetails.findByPk(req.params.id);
  res.send(r);
});

app.put("/base_projectdetails", async (req, res) => {
  // let r = await consproject.findByPk(req.params.id);
  //** 合同关联覆盖 */
  req.body.contractConsCode && await sequelize.query(`update base_projectdetails set contract_cons_code=null where contract_cons_code='${req.body.contractConsCode}'`);
  //** 图块关联覆盖 */
  req.body.projectareaObjectid && await sequelize.query(`update base_projectdetails set projectarea_objectid=null,projectarea_name=null where projectarea_objectid='${req.body.projectarea_objectid}'`);

  req.body.updatedTime = new Date();
  req.body.updateUser = 'admin';
  let r = await base_projectdetails.update(req.body, {
    where: {
      id: req.body.id,
    },
  });
  res.send(r);
});

app.post("/base_projectdetails", async (req, res) => {
  // delete req.body.id;
  //** 合同关联覆盖 */
  req.body.contractConsCode && await sequelize.query(`update base_projectdetails set contract_cons_code=null where contract_cons_code='${req.body.contractConsCode}'`);
  //** 图块关联覆盖 */
  req.body.projectareaObjectid && await sequelize.query(`update base_projectdetails set projectarea_objectid=null,projectarea_name=null where projectarea_objectid='${req.body.projectarea_objectid}'`);

  req.body.deletemark = 0;
  req.body.id = uuidv4().toUpperCase();
  req.body.createdTime = new Date();
  req.body.createdUser = 'admin';
  req.body.updatedTime = new Date();
  req.body.updatedUser = 'admin';
  let r = await base_projectdetails.create(req.body);
  // console.log(r);
  res.send(r);
});

app.get("/base_projectdetails/delete/:id", async (req, res) => {
  let r = await base_projectdetails.update({deletemark:1},{
    where: {
      id: req.params.id,
    },
  });
  res.send(r);
});



//排重查询
async function repeatres(req, res,field,fieldcol) {
  try {
    let repeatids = await sequelize.query(`select ${fieldcol} from base_projectdetails where ${fieldcol} not in ('','未找到') and deletemark=0  group by ${fieldcol} having count(*)>1`);
    let where = { [field]: { [Op.in]: repeatids[0].map(r => r[fieldcol]) },deletemark:0 };
    let r = await getlist(req, where, [field]);
    res.send(r);
  } catch (err) {
    console.log(err);
    res.send("err");
  }
}

